//
//  DataTool.m
//  XLNews
//
//  Created by 薛林 on 16/12/20.
//  Copyright © 2016年 YunTianXia. All rights reserved.
//

#import "DataTool.h"
#import "PictureFetchDataParameter.h"
#import "NetworkManager.h"
#import <MJExtension.h>
#import "Picture.h"
#import <FMDB.h>

@interface DataTool ()


@end

@implementation DataTool
static FMDatabaseQueue *_queue;
+(void)initialize {
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.sqlite"];
    _queue = [FMDatabaseQueue databaseQueueWithPath:path];
    
    [_queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"create table if not exists table_video(id integer primary key autoincrement, idstr text, time integer, video blob);"];
        
        [db executeUpdate:@"create table if not exists table_picture(id integer primary key autoincrement, idstr text, time integer, picture blob);"];
        
        [db executeUpdate:@"create table if not exists table_ttheadernews(id integer primary key autoincrement, title text, url text, desc text, picUrl text, ctime text);"];
        
        [db executeUpdate:@"create table if not exists table_normalnews(id integer primary key autoincrement, channelid text, title text, imageurls blob, desc text, link text, pubdate text, createdtime integer, source text);"];
        [db executeUpdate:@"create table if not exists table_videocomment(id integer primary key autoincrement, idstr text, page integer, hotcommentarray blob, latestcommentarray blob, total integer);"];
    }];
}
+ (void)pictureWithParameters:(PictureFetchDataParameter *)pictureParameters success:(void (^)(NSArray *, NSString *))success failure:(void (^)(NSError *))failure {
    //准备请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @(10);
    parameters[@"page"] = @(pictureParameters.page);
    if (pictureParameters.maxtime) {
        parameters[@"maxtime"] = pictureParameters.maxtime;
    }
    NSLog(@"%@",parameters);
    [[NetworkManager shareManager] Get:@"http://api.budejie.com/api/api_open.php" Parameters:parameters Success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
        NSArray *pictures = [Picture mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        NSString *maxTime = responseObject[@"info"][@"maxtime"];
        for (Picture *picture in pictures) {
            picture.maxtime = maxTime;
        }
        success(pictures,maxTime);
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self addPictureArray:pictures];
        });
    } Failure:^(NSError *error) {
        //网络请求失败 显示数据库中的数据
        pictureParameters.recentTime = nil;
        pictureParameters.remoteTime = nil;
        //从数据库中查找数据
        NSArray *pictures = [self selectDataFromCacheWithPictureParameters:pictureParameters];
        if (pictures.count > 0) {
            Picture *lastPicture = pictures.lastObject;
            NSString *maxtime = lastPicture.maxtime;
            success(pictures.copy,maxtime);
        }
        success(pictures.copy,@"");
    }];
    
}
//从数据库查找
+ (NSArray *)selectDataFromCacheWithPictureParameters:(PictureFetchDataParameter *)parameters {
    __block NSMutableArray *pictureArray = nil;
    
    [_queue inDatabase:^(FMDatabase *db) {
        pictureArray = [NSMutableArray array];
        FMResultSet *result = nil;
        
        if (parameters.recentTime) {//时间更大，代表消息发布越靠后，因为时间是按real来储存的
            NSInteger time = [[[parameters.recentTime stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@":" withString:@""].integerValue;
            
            result = [db executeQuery:@"select * from table_picture where time > ? order by time desc limit 0,20;", @(time)];
            
        }
        
        if(parameters.remoteTime) {
            NSInteger time = [[[parameters.remoteTime stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@":" withString:@""].integerValue;
            result = [db executeQuery:@"select * from table_picture where time < ? order by time desc limit 0,20;",@(time)];
        }
        
        if (parameters.remoteTime==nil && parameters.recentTime==nil){
            result = [db executeQuery:@"select * from table_picture order by time desc limit 0,20;"];
            
        }
        
        while (result.next) {
            NSData *data = [result dataForColumn:@"picture"];
            Picture *picture = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            [pictureArray addObject:picture];
        }
        
    }];
    return pictureArray;
}

//图片保存到数据库
+(void)addPicture:(Picture *)picture {
    [_queue inDatabase:^(FMDatabase *db) {
        NSString *idstr = picture.ID;
        FMResultSet *result = nil;
        NSString *querySql = [NSString stringWithFormat:@"SELECT * FROM table_picture WHERE idstr = '%@';",idstr];
        result = [db executeQuery:querySql];
        if (result.next==NO) {//不存在此条数据
            NSString *string = picture.created_at;
            NSInteger time = [[[string stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@":" withString:@""].integerValue;
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:picture];
            [db executeUpdate:@"insert into table_picture (idstr,time,picture) values(?,?,?);", idstr, @(time), data];
        }
        [result close];
    }];
}

+ (void)addPictureArray:(NSArray *)pictureArray {
    for (Picture *picture in pictureArray) {
        [self addPicture:picture];
    }
}


@end
